# -*- coding: utf-8 -*-
import hashlib
import json
import random
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '800000002': {
        'subMchId': '800000002000000006',
        'API_KEY': 'deef64fe380a480e8c60edc30b10c01a',
        'gateway': 'https://mempay.onepaypass.com/mps/cloudplatform/api/trade.html',
    },
    '800000069': {
        'subMchId': '800000069000000001',
        'API_KEY': 'f1010a47dcb34bd0a1d03f7d3c479395',
        'gateway': 'https://mempay.onepaypass.com/mps/cloudplatform/api/trade.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_sub_mchid(mch_id):
    return APP_CONF[mch_id]['subMchId']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys(), key=str.lower):
        if k != 'sign' and parameter[k] != '':
            if k != 'amount':
                s += '%s=%s&' % (k, parameter[k])
            else:
                s += '%s=%s&' % (k, '%.2f' % float(parameter[k]))
    s += 'key=' + key
    _LOGGER.info("qcmypay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            if k != 'amount':
                s += '%s=%s&' % (k, parameter[k])
            else:
                s += '%s=%s&' % (k, '%.2f' % float(parameter[k]))
    s += 'key=' + key
    _LOGGER.info("qcmypay generate_notify_sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("qcmypay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'wxH5'
    elif service == 'alipay':
        payType = 'alipayApp'
    elif service == 'qq':
        payType = 'qqwalletQR'
    elif service == 'bank':
        payType = 'unionOnline'
    elif service == 'quick':
        payType = 'qpay'
    else:
        payType = 'unionOnline'
    return payType


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if pay_amount >= 10 and int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def _get_device_tel(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('tel') or ''


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('tradeType', 'cs.pay.submit'),
        ('version', '1.3'),
        ('mchId', app_id),
        ('channel', _get_pay_type(service)),
        ('subMchId', _get_sub_mchid(app_id)),
        ('body', 'charge'),
        ('outTradeNo', str(pay.id)),
        ('amount', '%.2f' % pay_amount),
        # ('userId', _get_device_tel(info)),
        ('callbackUrl', '{}/pay/api/{}/qcmypay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/qcmypay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('subject', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    _LOGGER.info("qcmypay create: %s", j)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=j, headers=headers, timeout=10)
    _LOGGER.info("qcmypay create rsp: %s, %s", response.text, response.url)
    data = json.loads(response.text)
    if service == 'qq':
        return {'charge_info': data['codeUrl']}
    else:
        return {'charge_info': data['payCode']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("qcmypay notify body: %s", str(request.body))
    data = json.loads(str(request.body))
    verify_notify_sign(data, api_key)
    pay_id = data['outTradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('qcmypay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['outChannelNo']
    total_fee = float(data['amount'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 01：未支付
    # 02：已支付
    # 03：已冲正
    # 04：已关闭
    # 05：转入退款
    # 09：支付失败
    # 10：订单超时
    if trade_status == '02':
        _LOGGER.info('qcmypay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('tradeType', 'cs.trade.single.query'),
        ('version', '1.3'),
        ('mchId', app_id),
        ('subMchId', _get_sub_mchid(app_id)),
        ('outTradeNo', str(pay_order.id)),
        ('queryType', '1'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('qcmypay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info('qcmypay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['status']
        total_fee = float(data['amount'])
        trade_no = data['outChannelNo']
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '02':
            _LOGGER.info('qcmypay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
